package com.starblink.android.basic.network.config

import android.os.Build
import com.apollographql.apollo3.api.http.HttpHeader
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.NetworkUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.log.SKLogger
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.DeviceUtils
import com.starblink.basic.util.log.YYLogUtils
import okhttp3.Headers
import java.util.*
import kotlin.collections.HashMap


object HeadsHandle {


    private var defaultHeadsMap: Map<String, String?> = mapOf()
        get() = mapOf(
            "token" to UserDataCenter.getToken(),
            "deviceId" to "${UserDataCenter.getDeviceId(CommUtils.getContext())}",
            "os" to "and",
            "osVersion" to Build.VERSION.RELEASE,
            "networkType" to NetworkUtils.getNetworkType().name,
            "model" to Build.MODEL,
            "brand" to Build.BRAND,
            "country" to UserDataCenter.getLocalCountry(),
            "local_country_code" to UserDataCenter.LOCAL_COUNTRY_CODE,
            "clientVersion" to AppUtils.getAppVersionName(),
            "tz" to TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT),
            "language" to Locale.getDefault().language,
        )

    private val defaultHeads: ArrayList<HttpHeader> = arrayListOf()
    val headers: HashMap<String, String> = hashMapOf()

    /**
     * 获取请求头
     * 注意：处理好线程同步问题！接口请求在协程中执行，协程执行在哪个线程中不确定
     */
    fun getHttpDfHeads(reset: Boolean): ArrayList<HttpHeader> {
        synchronized(defaultHeads) {
//            SKLogger.e("dss", "getHttpDfHeads run in=${Thread.currentThread().name}")
//            SKLogger.e("dss", "defaultHeads.isEmpty()=${defaultHeads.isEmpty()}")
//            SKLogger.e("dss", "reset=${reset}")
            if (defaultHeads.isEmpty() || reset) {
                defaultHeads.clear()
                headers.clear()
//                SKLogger.e("dss", "defaultHeadsMap=${defaultHeadsMap}")
                defaultHeadsMap.forEach {
                    if (it.value != null) {
//                        SKLogger.e("dss", "${it.key} ${it.value}")
                        defaultHeads.add(HttpHeader(it.key, it.value!!))
                        headers[it.key] = it.value!!
                    }
                }
            }
//            SKLogger.e("dss", "getHttpDfHeads=${defaultHeads}")
            return defaultHeads
        }
    }
}